package com.sia.springcloud.heartbeat;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @Author: Sirius
 * @Date: 2021/12/30 13:26
 * @Description: 新建一个心跳检测任务，通过注解注入该对象后，该任务开机自启动
 * <p>
 * 2022/5/9 注释掉@Component，防止自动注入，避免使用心跳检测
 **/
@Slf4j
//@Component
public class HeartbeatRunner implements ApplicationRunner {


    private static final String heartbeatId = UUID.randomUUID().toString();


    @Value("${heartbeat.instance-id}")
    private String instanceId;

    @Value("${heartbeat.protocol-name}")
    private String protocolName;


    @Value("${heartbeat.destUrl}")
    private String destUrl;


    @Value("${heartbeat.frequency:5}")
    private Integer frequency;


    @Resource
    private Scheduler scheduler;


    /**
     * 新建一个心跳检测任务
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {

        log.info("心跳检测：开启");

        JobDetail jobDetail = JobBuilder.newJob(HeartbeatJob.class)
                .withIdentity(heartbeatId)
                .storeDurably()
                .build();


        JobDataMap jobDataMap = jobDetail.getJobDataMap();
        jobDataMap.put("heartbeatId", heartbeatId);
        jobDataMap.put("instanceId", instanceId);
        jobDataMap.put("protocolName", protocolName);
        jobDataMap.put("destUrl", destUrl);


        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule();
        scheduleBuilder.withIntervalInSeconds(frequency);
        scheduleBuilder.repeatForever();
        Trigger trigger = TriggerBuilder.newTrigger()
                .forJob(jobDetail)
                .withIdentity(heartbeatId)
                .withSchedule(scheduleBuilder)
                .startNow()
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
    }


    public void beat() throws SchedulerException {
        log.info("心跳检测：立即发送心跳");

        JobDetail jobDetail = JobBuilder.newJob(HeartbeatJob.class)
                .storeDurably()
                .build();


        JobDataMap jobDataMap = jobDetail.getJobDataMap();
        jobDataMap.put("heartbeatId", heartbeatId);
        jobDataMap.put("instanceId", instanceId);
        jobDataMap.put("protocolName", protocolName);
        jobDataMap.put("destUrl", destUrl);


        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule();
        scheduleBuilder.withRepeatCount(0);
        Trigger trigger = TriggerBuilder.newTrigger()
                .forJob(jobDetail)
                .withSchedule(scheduleBuilder)
                .startNow()
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
    }
}
